package org.autumn.cas;

import java.util.concurrent.atomic.AtomicInteger;

public class LockCas {

    private AtomicInteger lock = new AtomicInteger(0);

    /**
     * 加锁操作
     */
    public void lock() {
        while (!lock.compareAndSet(0,1)){

        }
    }

    /**
     * 结束操作
     */
    public void unlock() {
        lock.set(0);
    }

    static int a1 = 0;

    public static void main(String[] args) throws InterruptedException {
        LockCas lock = new LockCas();
        Thread t1 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                lock.lock();
                a1++;
                lock.unlock();
            }
        }, "t1");

        Thread t2 = new Thread(() -> {
            for (int i = 0; i < 10000; i++) {
                lock.lock();
                a1--;
                lock.unlock();
            }
        }, "t2");

        t1.start();
        t2.start();

        t1.join();
        t2.join();

        System.out.println(a1);
    }
}
